/**
 * @Description: 网络请求工具
 * @author 范东洋
 * @date 2020/4/1
 */
import {AsyncStorage} from 'react-native'
import QueryString from 'query-string';
import config from '../common/config'
import Toast from "teaset/components/Toast/Toast";

const throwError = json => {
    const error = new Error(json.code);
    error.message = json.msg;
    error.code = json.code;
    throw error;
};

const checkStatus = ({resp, json,}) => {
    // 如果 返回结果中包含 code 和 message, 则认为出错了

    if (resp.status >= 200 && resp.status < 300) {
        return json;
    } else if (resp.status >= 500) {
        throwError(json);
    } else {
        throwError(json);
    }

    return json;
};

const getToken = async () => {
    const users = await AsyncStorage.getItem('users');
    if (users) {
        const __users = JSON.parse(users);
        return __users.token ? __users.token : null;
    }
    return null;
};
const _fetchData = async (url, options) => {
    // const __token = await getToken();
    url = config.api.baseURI + url
    let requestParam = {}
    requestParam['headers'] = {
        "Accept": "application/json",
        "Content-Type": 'application/json',
        "Connection": "close",
        "type": "getUserData",
        ...options['headers'] || {}
    }
    requestParam['method'] = options.method
    options['body'] ? requestParam['body'] = options['body'] : null
    return fetch(url, {
        ...requestParam
    }).then(resp => resp.json()
    ).then(json => json
    ).catch(err => {
        console.warn('发生错误=>', url, err)
        Toast.fail('请检查网络是否连接正常')
    })

    /*
    * .then(resp => resp.json().then(json => ({resp, json})).catch(error => ({resp, json: {}, error})))
        .then(checkStatus)*/

}
let request = {
    get(url: string, params: Object) {
        if (params) {
            url += '?' + QueryString.stringify(params)
        }
        const options = {
            method: 'GET'
        }
        return _fetchData(url, options)
    },
    post(url: string, params = {}) {
        params.accessToken = config.user.accessToken;
        for (let key in params) {
            if (params[key] === undefined || params[key] === null) {
                delete params[key];
            }
        }
        params = QueryString.stringify(params);

        const options = {
            method: 'POST',
            headers: {
                "Content-Type": "multipart/form-data",
            },
            body: params,
        };
        return _fetchData(url, options)
    },
}
export default request
